package cn.vconinfo.app.dubbo;

import cn.vconinfo.app.constant.DubboConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;

import java.util.UUID;

@Activate(group = {Constants.CONSUMER})
public class ConsumerRpcTraceFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = MDC.get(DubboConstant.TRACE_ID);
        String serverIp = MDC.get(DubboConstant.SERVER_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = this.getUUID() ;
            //设置日志traceId变量
            MDC.put(DubboConstant.TRACE_ID, traceId);
        }
        if(StringUtils.isBlank(serverIp)){
            serverIp = NetUtils.getLocalHost();
            MDC.put(DubboConstant.SERVER_ID, serverIp);
        }

        RpcContext.getContext().setAttachment(DubboConstant.TRACE_ID, traceId);
        RpcContext.getContext().setAttachment(DubboConstant.SERVER_ID, serverIp);

        return invoker.invoke(invocation);
    }

    /**
     * 获取UUID
     * @return String UUID
     */
    public String getUUID(){
        String uuid = UUID.randomUUID().toString();
        //替换-字符
        return uuid.replaceAll("-", "");
    }

}
